<template>
  <div class="user-management-container">
    <!-- 顶部操作栏 -->
    <el-card class="action-bar" shadow="never">
      <div class="action-content">
        <h2 class="page-title">
          <i class="el-icon-user-solid"></i>
          用户管理
        </h2>
        <el-button
            v-if="isAdmin || isSuperAdmin"
            :icon="Plus"
            class="add-user-btn"
            type="primary"
            @click="handleOpenAddUser"
        >
          新增用户
        </el-button>
      </div>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="user-table-card" shadow="never">
      <div class="table-wrapper">
        <el-table
            v-loading="loading"
            :data="userTableData"
            class="elegant-user-table"
            empty-text="暂无用户数据"
            style="width: 100%"
        >
          <el-table-column align="center" label="ID" prop="id" width="70"/>
          <el-table-column align="center" label="用户名" prop="username" width="130"/>
          <el-table-column align="center" label="昵称" prop="nickname" width="180"/>
          <el-table-column align="center" label="创建日期" prop="createdAt" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="更新日期" prop="updatedAt" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.updatedAt) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="上次登陆IP" prop="lastLogin" width="130"/>
          <el-table-column align="center" label="用户角色" width="130">
            <template #default="scope">
              <el-tag
                  :type="getRoleTagType(scope.row.roleId)"
                  class="role-tag"
                  effect="light"
              >
                {{ getRoleName(scope.row.roleId) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" min-width="280">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                    v-if="isSuperAdmin"
                    :icon="Delete"
                    link
                    size="small"
                    type="danger"
                    @click="handleDeleteUserOpen(scope.row)"
                >
                  删除
                </el-button>
                <el-button
                    v-if="isAdmin || isSuperAdmin || isUserSelf(scope.row.userId)"
                    :icon="Edit"
                    link
                    size="small"
                    type="primary"
                    @click="handleEditClick(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                    v-if="isAdmin || isSuperAdmin || isUserSelf(scope.row.userId)"
                    :icon="Key"
                    link
                    size="small"
                    type="warning"
                    @click="handleAuthClick(scope.row)"
                >
                  权限
                </el-button>
                <el-button
                    v-if="isAdmin || isSuperAdmin || isUserSelf(scope.row.userId)"
                    :icon="Refresh"
                    link
                    size="small"
                    type="info"
                    @click="handleResetPasswordClick(scope.row)"
                >
                  密码
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页控件 -->
      <div v-if="userTableData && userTableData.length > 0" class="pagination-container">
        <el-pagination
            :current-page="currentPage"
            :page-size="10"
            :total="userTableData.length"
            background
            layout="prev, pager, next, total"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 对话框组件 -->
    <AddUserDialog
        ref="addServerConnectRef"
        :add-dialog-visible="addDialogVisible"
        @close="handleCloseAddUserDialog"
        @update:addDialogVisible="addDialogVisible = $event"
    />

    <EditUserDialog
        ref="editServerConnectRef"
        :edit-dialog-visible="editDialogVisible"
        :user-info="selectedEditUser"
        @update:editDialogVisible="editDialogVisible = $event"
    />

    <ResetPassWordDialog
        ref="resetPasswordRef"
        :reset-password-visible="resetPasswordVisible"
        :user-info="selectedResetPassUser"
        @update:resetPasswordVisible="resetPasswordVisible = $event"
    />

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteUserDialogVisible"
        :before-close="handleDeleteUserClose"
        class="delete-dialog"
        title="删除确认"
        width="450px"
    >
      <div class="delete-content">
        <div class="delete-warning">
          <i class="el-icon-warning-outline"></i>
          <span>确认删除用户 <strong>{{ selectedDeleteUser.username }}</strong> 吗？</span>
        </div>
        <p class="delete-tip">此操作不可恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteUserDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmDeleteUser">
            确认删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from "vue"
import {SysUserInfo} from "@/type/systemConfig/sysUserInfo";
import {deleteSysUserById, getAllUserList} from "@/api/system/sysUser";
import AddUserDialog from "@/components/system/AddUserDialog.vue"
import message from '@/utils/ElmessasgeUtils'
import EditUserDialog from "@/components/system/EditUserDialog.vue";
import {getAllRoleList} from "@/api/system/sysRole";
import ResetPassWordDialog from "@/components/system/ResetPassWordDialog.vue";
import {getUserInfo} from "@/utils/system";
import {Plus, Delete, Edit, Key, Refresh} from '@element-plus/icons-vue'

// 组件状态
const editDialogVisible = ref(false);
const addDialogVisible = ref(false);
const resetPasswordVisible = ref(false);
const deleteUserDialogVisible = ref(false);
const loading = ref(false);
const currentPage = ref(1);

const selectedDeleteUser = ref({} as SysUserInfo);
const selectedEditUser = ref({} as SysUserInfo);
const selectedResetPassUser = ref({} as SysUserInfo);

const userTableData = ref<SysUserInfo[]>([]);
const roleMap = ref([] as any[]);

// 获取角色列表
getAllRoleList().then((res: any) => {
  if (res.data.code == 200) {
    roleMap.value = res.data.data;
  } else {
    message.message("获取角色列表失败");
  }
});

// 更新用户列表
function updateUserList() {
  loading.value = true;
  getAllUserList().then(res => {
    if (res.data.code === 200) {
      userTableData.value = res.data.data;
    } else {
      message.message('获取用户列表失败', 'error');
    }
  }).finally(() => {
    loading.value = false;
  });
}

// 日期格式化
function formatDate(dateString: string) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

// 获取角色名称
function getRoleName(roleId: number) {
  if (!roleMap.value) return '未知角色';
  const role = roleMap.value.find(value => Number(value.id) === roleId);
  return role ? role.roleName : '未知角色';
}

// 获取角色标签类型
function getRoleTagType(roleId: number) {
  const roleTypes = ['', 'success', 'info', 'warning', 'danger'];
  return roleTypes[roleId % roleTypes.length] || '';
}

// 打开删除用户确认窗口
function handleDeleteUserOpen(row: SysUserInfo) {
  selectedDeleteUser.value = row;
  deleteUserDialogVisible.value = true;
}

// 确认删除用户
function handleConfirmDeleteUser() {
  deleteSysUserById(selectedDeleteUser.value.id).then(res => {
    if (res.data.code === 200) {
      deleteUserDialogVisible.value = false;
      message.message(`删除用户 ${selectedDeleteUser.value.username} 成功`, 'success');
      updateUserList();
    } else {
      message.message(`删除用户失败: ${res.data.msg}`, 'error');
    }
  });
}

function handleDeleteUserClose() {
  deleteUserDialogVisible.value = false;
}

function handleEditClick(row: SysUserInfo) {
  editDialogVisible.value = true;
  selectedEditUser.value = row;
}

function handleAuthClick(row: SysUserInfo) {
  // 权限管理逻辑
}

function handleOpenAddUser() {
  addDialogVisible.value = true;
}

function handleCloseAddUserDialog() {
  updateUserList();
  addDialogVisible.value = false;
}

function handleResetPasswordClick(row: SysUserInfo) {
  const loginUser = getUserInfo();
  if (!(loginUser.roleId == 1 || row.userId == loginUser.userId)) {
    message.message('无权限，非管理员或本账号', 'error');
    return;
  }
  selectedResetPassUser.value = row;
  resetPasswordVisible.value = true;
}

function handlePageChange(page: number) {
  currentPage.value = page;
}

const isAdmin = ref(false);
const isSuperAdmin = ref(false);

function isUserSelf(userId: string) {
  return getUserInfo().userId == userId;
}

onMounted(() => {
  isAdmin.value = (getUserInfo().roleId == 1)
  isSuperAdmin.value = (getUserInfo().roleId == 0)
  updateUserList();
});
</script>

<style lang="scss" scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  box-sizing: border-box;
}

.action-bar {
  margin-bottom: 20px;
  border-radius: 8px;
  border: none;

  .action-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      display: flex;
      align-items: center;

      i {
        margin-right: 10px;
        color: #409EFF;
      }
    }

    .add-user-btn {
      border-radius: 6px;
      padding: 10px 16px;
      font-weight: 500;
    }
  }
}

.user-table-card {
  border-radius: 8px;
  border: none;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
  }
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
}

.elegant-user-table {
  width: 100%;
  min-width: 100%;
  table-layout: fixed;

  :deep(.el-table__header) {
    width: 100% !important;

    th {
      background: linear-gradient(to bottom, #f8fafd, #f0f5ff);
      color: #606266;
      font-weight: 600;
      height: 50px;
      padding: 8px 0;
    }
  }

  :deep(.el-table__body) {
    width: 100% !important;

    tr:hover {
      background-color: #f5f9ff;
    }

    td {
      border-bottom: 1px solid #f0f4f8;
      padding: 12px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .role-tag {
    border-radius: 4px;
    font-weight: 500;
    margin: 2px 0;
  }

  .action-buttons {
    display: flex;
    flex-wrap: nowrap;
    justify-content: center;
    gap: 8px;

    .el-button {
      padding: 5px 8px;
      border-radius: 4px;
      font-size: 12px;
      white-space: nowrap;
    }
  }
}

.pagination-container {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
}

.delete-dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #ebeef5;
    padding: 16px 20px;
    margin: 0;

    .el-dialog__title {
      color: #f56c6c;
      font-weight: 600;
    }
  }

  .delete-content {
    padding: 20px;

    .delete-warning {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      i {
        color: #e6a23c;
        font-size: 20px;
        margin-right: 10px;
      }

      span {
        font-size: 16px;
      }
    }

    .delete-tip {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .dialog-footer {
    padding: 0 20px 20px;
  }
}

@media (max-width: 1200px) {
  .elegant-user-table {
    :deep(.el-table__header),
    :deep(.el-table__body) {
      min-width: 1000px;
    }
  }

  .table-wrapper {
    overflow-x: auto;
  }
}

@media (max-width: 768px) {
  .user-management-container {
    padding: 10px;
  }

  .action-content {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 15px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 5px;

    .el-button {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>